package com.example.myapplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings;

/**
 * 设备数据上传配置类
 * 管理服务器地址、上传间隔等配置
 */
public class DeviceDataConfig {
    
    private static final String PREFS_NAME = "device_data_config";
    private static final String KEY_SERVER_URL = "server_url";
    private static final String KEY_UPLOAD_INTERVAL = "upload_interval";
    private static final String KEY_AUTO_UPLOAD = "auto_upload";
    private static final String KEY_DEVICE_ID = "device_id";
    
    // 默认配置
    private static final String DEFAULT_SERVER_URL = "http://101.37.91.4:32002";
    private static final long DEFAULT_UPLOAD_INTERVAL = 60 * 60 * 1000; // 1小时
    private static final boolean DEFAULT_AUTO_UPLOAD = true;
    
    private final Context context;
    private final SharedPreferences sharedPreferences;
    
    public DeviceDataConfig(Context context) {
        this.context = context.getApplicationContext();
        this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }
    
    /**
     * 获取服务器地址
     */
    public String getServerUrl() {
        return sharedPreferences.getString(KEY_SERVER_URL, DEFAULT_SERVER_URL);
    }
    
    /**
     * 设置服务器地址
     */
    public void setServerUrl(String serverUrl) {
        sharedPreferences.edit().putString(KEY_SERVER_URL, serverUrl).apply();
    }
    
    /**
     * 获取上传间隔（毫秒）
     */
    public long getUploadInterval() {
        return sharedPreferences.getLong(KEY_UPLOAD_INTERVAL, DEFAULT_UPLOAD_INTERVAL);
    }
    
    /**
     * 设置上传间隔（毫秒）
     */
    public void setUploadInterval(long interval) {
        sharedPreferences.edit().putLong(KEY_UPLOAD_INTERVAL, interval).apply();
    }
    
    /**
     * 是否自动上传
     */
    public boolean isAutoUpload() {
        return sharedPreferences.getBoolean(KEY_AUTO_UPLOAD, DEFAULT_AUTO_UPLOAD);
    }
    
    /**
     * 设置是否自动上传
     */
    public void setAutoUpload(boolean autoUpload) {
        sharedPreferences.edit().putBoolean(KEY_AUTO_UPLOAD, autoUpload).apply();
    }
    
    /**
     * 获取设备ID（Android ID）
     */
    public String getDeviceId() {
        String deviceId = sharedPreferences.getString(KEY_DEVICE_ID, null);
        if (deviceId == null || deviceId.isEmpty()) {
            // 使用Android ID作为设备唯一标识
            deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            if (deviceId == null || deviceId.isEmpty()) {
                // 如果Android ID不可用，使用其他方式生成
                deviceId = java.util.UUID.randomUUID().toString();
            }
            sharedPreferences.edit().putString(KEY_DEVICE_ID, deviceId).apply();
        }
        return deviceId;
    }
    
    /**
     * 设置设备ID（自定义）
     */
    public void setDeviceId(String deviceId) {
        sharedPreferences.edit().putString(KEY_DEVICE_ID, deviceId).apply();
    }
}

